package org.hxzon.demo.tomcat;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Embedded;

public class EmbedTomcat {

    private final String tomcatHome = "D:\\develop\\tomcat-6.0.29";
    private Embedded tomcat;

    public static void main(String[] args) {

        EmbedTomcat manager = new EmbedTomcat();
        manager.startServer();
        while (true) {

        }
        // manager.stopServer();
    }

    public void startServer() {

        tomcat = createTomcat(tomcatHome);
        try {
            tomcat.start();
            System.out.println("---------- Tomcat Server start over. ------------");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void stopServer() {
        try {
            tomcat.stop();
            System.out.println("---------------- Tomcat Server stoped -----------------");
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }

    private static Embedded createTomcat(String tomcatHome) {
        Embedded tomcat = new Embedded();
        tomcat.setCatalinaHome(tomcatHome);
        Engine engine = tomcat.createEngine();
        engine.setName("Catalina");
        Host host = tomcat.createHost("localhost", tomcat.getCatalinaHome() + "/webapps");
        // host.setAppBase("webapps");
        host.setAutoDeploy(true);
        Context materialApp = tomcat.createContext("/material", host.getAppBase() + "/material4");
        host.addChild(materialApp);

        engine.addChild(host);
        engine.setDefaultHost(host.getName());

        tomcat.addEngine(engine);
        try {
            tomcat.addConnector(tomcat.createConnector(InetAddress.getByName("127.0.0.1"), 8080, false));
        } catch (UnknownHostException e) {
            e.printStackTrace();
            tomcat = null;
        }
        return tomcat;
    }
}
